# gozerbot/utils/exception.py
#
#

""" exception handling functions """

__status__ = "seen"

## gozerbot imports

from gozerbot.utils.log import rlog
from gozerbot.utils.locking import lockdec

## basic imports

import sys
import traceback
import logging
import thread
import os

## locks

exceptionlock = thread.allocate_lock()
exceptionlocked = lockdec(exceptionlock)

## defines

borkonexception = False
exceptionlist = []
exceptionevents = []

## exceptionmsg funcion

@exceptionlocked
def exceptionmsg():
    """ convert the exception into a string. """
    exctype, excvalue, tb = sys.exc_info()
    trace = traceback.extract_tb(tb)
    result = ""
    for i in trace:
        fname = i[0]
        linenr = i[1]
        func = i[2]
        result += "%s:%s %s | " % (fname, linenr, func)
    del trace
    res = "%s%s: %s" % (result, exctype, excvalue)
    if res not in exceptionlist: exceptionlist.append(res)
    #if '_props' in res: print 
    return res

## handle_exception function

def handle_exception(event=None, log=True, short=False, txt=""):
    """ generic exception handler, prints out the exception trace. """
    global borkonexception
    errormsg = exceptionmsg()
    if event:
       if '_props' in errormsg: print event ; os._exit(1)
    if log: rlog(1000, 'EXCEPTION', errormsg)
    if event:
        if borkonexception:
            rlog(1000, 'EXCEPTION', 'command: ' + event.txt)
            rlog(1000, 'EXCEPTION', 'options: ' + str(event.options))
        exceptionevents.append((event, errormsg))
        if event.bot: event.bot.error = errormsg
        event.reply(errormsg)
    if borkonexception:
        rlog(1000, 'EXCEPTION', "BORK ON EXCEPTION")
        sys.stdout.flush()
        os._exit(1)

#### BHJTW 22-01-2012
